# coding= utf-8

import sys
import codecs
import warnings
import pymongo
import json
import requests
import time

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
warnings.filterwarnings("ignore")


class CurrentMonth:

    def __init__(self):
        self.country_desc = ''
        # self.month = sys.argv[1]
        self.month = '2024-09'
        self.desc = {'us_num': '美国', 'uk_num': '英国', 'eur_num': '欧洲四国', 'jp_num': '日本', 'ca_num': '加拿大'}

        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["xp_analyse"]
        self.low_order = mydb["wt_low_order_v2"]

    def update_low_order_num(self):
        # url = 'http://local-sys.com/common/analyse/get_asin_order_desc'
        url = 'https://wangting.wszzl.cn/common/analyse/get_asin_order_desc'
        params = {'month': self.month}
        response = requests.get(url, params=params)
        res = json.loads(response.text)

        # 获取asin列表
        if int(res['status']):
            low_insert = []
            asin_list = res['result']
            for item in asin_list:
                group_name = item['_id']['group_name']
                asin = item['_id']['asin']

                # 获取各个国家的单量
                for d in self.desc:
                    order_num = item[d]

                    # 小于10单为低单量，查询低订单表中是否有此asin
                    if 0 < order_num < 10:
                        low_order = self.low_order.find_one(
                            {"country_desc": self.desc[d], 'group_name': group_name, 'asin': asin, 'month': self.month})
                        if low_order:
                            # 已在低订单表中，更新订单量
                            if not order_num == low_order['order_num']:
                                self.low_order.update_one(
                                    {"country_desc": self.desc[d], 'group_name': group_name, 'asin': asin,
                                     'month': self.month}, {"$set": {"order_num": order_num}})
                                print('低单量不一致，需要更新！')
                            else:
                                print('已存在相同数据，无需更新')
                        else:
                            value = dict([
                                ['asin', asin],
                                ['country_desc', self.desc[d]],
                                ['month', self.month],
                                ['group_name', group_name],
                                ['status', '在售'],
                                ['order_num', order_num],
                                ['limit_type', ''],
                                ['order_reason', ''],
                                ['create_time', int(time.time())],
                                ['update_time', int(time.time())],
                            ])
                            low_insert.append(value)
                            print('需要补充低订单')
                            print(value)
                    else:
                        print('大于10单，不是低订单')

            if len(low_insert) > 0:
                result = self.low_order.insert_many(low_insert)

                # 检查插入操作是否成功
                if result.acknowledged:
                    print('插入低订单表成功，共计' + str(len(low_insert)) + '条！')
                else:
                    print('插入低订单失败！')
        else:
            print(res['message'])


def translate_country_desc(num):
    dis = {'us_num': '美国', 'uk_num': '英国', 'eur_num': '欧洲四国', 'jp_num': '日本', 'ca_num': '加拿大'}
    return dis.get(num)


current = CurrentMonth()
current.update_low_order_num()
